package com.syh.jn.scm.infrastructure.repository.impl.supplier.base.downstream;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.DataModelException;
import com.syh.jn.scm.domain.supplier.entity.base.downstream.DownstreamAccount;
import com.syh.jn.scm.domain.supplier.repository.base.downstream.DownstreamAccountRepository;
import com.syh.jn.scm.infrastructure.repository.model.system.AccountModel;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class DownstreamAccountRepositoryImpl extends AbstractAggregateRepository<DownstreamAccount, AccountModel, Long> implements DownstreamAccountRepository {

    /**
     * 添加下游账号
     *
     * @param account
     * @return
     */
    @Override
    public Boolean addAccount(DownstreamAccount account) {
        ExtAssert.notNull(account, "对象为空");
        StringBuffer hql = new StringBuffer();
        hql.append("from AccountModel model where model.businessEntityId = ? and model.terminalType = 'DOWNSTREAM' and model.admin = 1");
        List<AccountModel> modelList = (List<AccountModel>) this.hibernateTemplate.find(hql.toString(), account.getBusinessEntityId());
        if (modelList != null && modelList.size() > 0) {
            throw new DataModelException("该客户已开通帐号!");
        }
        AccountModel accountModel = AccountModel.builder()
                .terminalType("DOWNSTREAM")
                .build();
        ExtBeanUtils.copyProperties(account, accountModel, false);
        accountModel.setRoleId(0l);
        accountModel.setAdmin(Short.valueOf("1"));
        super.hibernateTemplate.save(accountModel);
        return Boolean.TRUE;
    }

}
